package com.ilearn.autocomplie.code;

import com.ilearn.autocomplie.entities.EntityModel;
import lombok.Builder;
import lombok.Data;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author: lyndon
 * @version: 1.0
 * @date: 2019/1/27
 */

@Component
@Data
public class CustomFactoryBean implements FactoryBean<EntityModel> {


    private final ConcurrentMap<String, Class<?>> entityMap = new ConcurrentHashMap<String, Class<?>>();

    private AutoCompileLoader autoCompileLoader;

    public AutoCompileLoader getAutoCompileLoader() {
        return autoCompileLoader;
    }


    public void setAutoCompileLoader(AutoCompileLoader autoCompileLoader) {
        this.autoCompileLoader = autoCompileLoader;
    }

    @Override
    public EntityModel getObject() throws Exception {
        return (EntityModel) Objects.requireNonNull(getObjectType()).newInstance();
    }

    @Override
    public Class<?> getObjectType() {
        //AutoCompileLoader autoCompileLoader = new AutoCompileLoader(tableName, columnNames, columnTypes);
        Class<?> tclass = entityMap.get(autoCompileLoader.getTableName());
        if (tclass == null) {
            tclass = autoCompileLoader.proxyLoader(EntityModel.class, autoCompileLoader.getTableName(), autoCompileLoader.getColumnNames(), autoCompileLoader.getColumnTypes());
            this.entityMap.put(autoCompileLoader.getTableName(), tclass);
        }
        return tclass;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}
